using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 关联文件选择对话框
    /// </summary>
    public partial class RelatedFilesSelectionDialog : Window
    {
        private readonly ILogger<RelatedFilesSelectionDialog> _logger;
        private readonly string _projectPath;
        private readonly int _chapterNumber;
        
        public ObservableCollection<FileInfo> AvailableFiles { get; set; } = new();
        public ObservableCollection<FileInfo> SelectedFiles { get; set; } = new();
        
        // 重写配置属性
        public bool AutoSave => AutoSaveCheckBox.IsChecked == true;
        public bool BackupOriginal => BackupOriginalCheckBox.IsChecked == true;
        public bool EnableResume => EnableResumeCheckBox.IsChecked == true;
        public int MaxContextLength => int.TryParse(MaxContextLengthTextBox.Text, out var length) ? length : 4000;
        public string RewriteStyle => (RewriteStyleComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString() ?? "保持原风格";
        
        public List<string> SelectedFilePaths => SelectedFiles.Select(f => f.FullPath).ToList();

        public RelatedFilesSelectionDialog(string projectPath, int chapterNumber, ILogger<RelatedFilesSelectionDialog> logger = null)
        {
            InitializeComponent();
            _logger = logger;
            _projectPath = projectPath;
            _chapterNumber = chapterNumber;
            
            InitializeDialog();
        }

        private void InitializeDialog()
        {
            try
            {
                // 设置数据绑定
                AvailableFilesListView.ItemsSource = AvailableFiles;
                SelectedFilesListView.ItemsSource = SelectedFiles;
                
                // 加载项目文件
                LoadProjectFiles();
                
                // 绑定筛选事件
                OutlineFilesCheckBox.Checked += FilterFiles;
                OutlineFilesCheckBox.Unchecked += FilterFiles;
                ChapterFilesCheckBox.Checked += FilterFiles;
                ChapterFilesCheckBox.Unchecked += FilterFiles;
                SettingFilesCheckBox.Checked += FilterFiles;
                SettingFilesCheckBox.Unchecked += FilterFiles;
                AllFilesCheckBox.Checked += FilterFiles;
                AllFilesCheckBox.Unchecked += FilterFiles;
                
                UpdateStatus();
                _logger?.LogInformation($"关联文件选择对话框已初始化，项目路径: {_projectPath}, 章节: {_chapterNumber}");
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "初始化关联文件选择对话框时发生错误");
                MessageBox.Show($"初始化对话框时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadProjectFiles()
        {
            try
            {
                AvailableFiles.Clear();
                
                if (!Directory.Exists(_projectPath))
                {
                    _logger?.LogWarning($"项目路径不存在: {_projectPath}");
                    return;
                }

                // 扫描项目文件
                var files = Directory.GetFiles(_projectPath, "*.*", SearchOption.AllDirectories)
                    .Where(f => IsValidFile(f))
                    .Select(f => new FileInfo
                    {
                        FullPath = f,
                        FileName = Path.GetFileName(f),
                        FileType = GetFileType(f),
                        FileSize = FormatFileSize(new System.IO.FileInfo(f).Length),
                        LastModified = new System.IO.FileInfo(f).LastWriteTime.ToString("yyyy-MM-dd HH:mm")
                    })
                    .OrderBy(f => f.FileType)
                    .ThenBy(f => f.FileName);

                foreach (var file in files)
                {
                    AvailableFiles.Add(file);
                }

                // 自动选择推荐文件
                AutoSelectRecommendedFiles();
                
                _logger?.LogInformation($"已加载 {AvailableFiles.Count} 个可选文件");
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "加载项目文件时发生错误");
                MessageBox.Show($"加载项目文件时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private bool IsValidFile(string filePath)
        {
            var extension = Path.GetExtension(filePath).ToLower();
            var validExtensions = new[] { ".txt", ".docx", ".md" };
            
            // 排除临时文件和系统文件
            var fileName = Path.GetFileName(filePath);
            if (fileName.StartsWith("~") || fileName.StartsWith("."))
                return false;
                
            return validExtensions.Contains(extension);
        }

        private string GetFileType(string filePath)
        {
            var fileName = Path.GetFileName(filePath);
            var relativePath = Path.GetRelativePath(_projectPath, filePath);
            
            if (relativePath.Contains("Outlines"))
                return "大纲";
            else if (relativePath.Contains("Chapters"))
                return "章节";
            else if (relativePath.Contains("Settings"))
                return "设定";
            else if (fileName.Contains("大纲") || fileName.Contains("outline"))
                return "大纲";
            else if (fileName.Contains("章") || fileName.Contains("Chapter"))
                return "章节";
            else if (fileName.Contains("设定") || fileName.Contains("世界") || fileName.Contains("角色"))
                return "设定";
            else
                return "其他";
        }

        private string FormatFileSize(long bytes)
        {
            if (bytes < 1024) return $"{bytes} B";
            if (bytes < 1024 * 1024) return $"{bytes / 1024} KB";
            return $"{bytes / (1024 * 1024)} MB";
        }

        private void AutoSelectRecommendedFiles()
        {
            try
            {
                // 自动选择推荐的参考文件
                var recommendedFiles = AvailableFiles.Where(f =>
                    f.FileType == "大纲" ||
                    (f.FileType == "章节" && IsRelevantChapter(f.FileName)) ||
                    (f.FileType == "设定" && IsImportantSetting(f.FileName))
                ).Take(6); // 限制最多6个文件

                foreach (var file in recommendedFiles)
                {
                    SelectedFiles.Add(file);
                }
                
                _logger?.LogInformation($"自动选择了 {SelectedFiles.Count} 个推荐文件");
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "自动选择推荐文件时发生错误");
            }
        }

        private bool IsRelevantChapter(string fileName)
        {
            // 选择当前章节前面的几章作为参考
            for (int i = Math.Max(1, _chapterNumber - 3); i < _chapterNumber; i++)
            {
                if (fileName.Contains($"第{i}章") || fileName.Contains($"章{i:D4}") || fileName.Contains($"Chapter{i}"))
                    return true;
            }
            return false;
        }

        private bool IsImportantSetting(string fileName)
        {
            var importantKeywords = new[] { "世界观", "角色", "设定", "背景", "world", "character" };
            return importantKeywords.Any(keyword => fileName.Contains(keyword));
        }

        private void FilterFiles(object sender, RoutedEventArgs e)
        {
            // 实现文件筛选逻辑
            // 这里可以根据复选框状态过滤显示的文件
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedItems = AvailableFilesListView.SelectedItems.Cast<FileInfo>().ToList();
            foreach (var item in selectedItems)
            {
                if (!SelectedFiles.Contains(item))
                {
                    SelectedFiles.Add(item);
                }
            }
            UpdateStatus();
        }

        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedItems = SelectedFilesListView.SelectedItems.Cast<FileInfo>().ToList();
            foreach (var item in selectedItems)
            {
                SelectedFiles.Remove(item);
            }
            UpdateStatus();
        }

        private void AddAllButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in AvailableFiles)
            {
                if (!SelectedFiles.Contains(item))
                {
                    SelectedFiles.Add(item);
                }
            }
            UpdateStatus();
        }

        private void RemoveAllButton_Click(object sender, RoutedEventArgs e)
        {
            SelectedFiles.Clear();
            UpdateStatus();
        }

        private void UpdateStatus()
        {
            // 更新状态文本
            StatusText.Text = $"已选择 {SelectedFiles.Count} 个文件";
            ConfirmButton.IsEnabled = SelectedFiles.Count > 0;

            // 更新计数显示
            if (AvailableCountText != null)
                AvailableCountText.Text = $"({AvailableFiles.Count} 个文件)";

            if (SelectedCountText != null)
                SelectedCountText.Text = $"({SelectedFiles.Count} 个文件)";
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedFiles.Count == 0)
            {
                MessageBox.Show("请至少选择一个参考文件", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            DialogResult = true;
            Close();
        }
    }

    /// <summary>
    /// 文件信息类
    /// </summary>
    public class FileInfo
    {
        public string FullPath { get; set; } = "";
        public string FileName { get; set; } = "";
        public string FileType { get; set; } = "";
        public string FileSize { get; set; } = "";
        public string LastModified { get; set; } = "";
    }
}
